package com.jps.transactional;

import com.jps.entity.Order;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * create by lenovo 2020/10/2
 * rocketmq实现分布式事务
 *
 *  STEP 1
 */

@RestController
public class TransactionalController {
    @Autowired
    private Source source;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/transactional")
    public String transactional(){
        Order order = new Order("123","广东深圳");

        String transactionId = UUID.randomUUID().toString();
        System.out.println("开始事务ID="+transactionId);
        Message<Order> message = MessageBuilder.withPayload(order).setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId).build();
        source.output().send(message);
        // 调用事务 OrderTransactionGroup是事务组名称与@RocketMQTransactionListener(txProducerGroup = "OrderTransactionGroup")保持一致
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("OrderTransactionGroup", "hello-rocketmq", message, order.getOrderId());

        return "success.";
    }
}
